import type { IMiddleware } from "koa-router";
import { Admin } from "../model";
import { makeResponse, HttpStatusCode } from "../util/response";
import { getToken } from "../util/jwt";

export const login: IMiddleware = async ctx => {

  const adminInfo = ctx.state.admin.toJSON();
  delete adminInfo.password;
  const token = getToken({ adminId: adminInfo._id });

  makeResponse(ctx, HttpStatusCode.Ok, { ...adminInfo, token });
};

export const register: IMiddleware = async ctx => {
  const admin = new Admin(ctx.request.body);
  await admin.save();
  const adminJSON = admin.toJSON();
  delete adminJSON.password;

  makeResponse(ctx, HttpStatusCode.Created, adminJSON);
};
